﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace liuzw.utils
{
    internal static class HttpExtensions
    {
        public static string HttpGetWithCookie(string url, Dictionary<string, string> cookieContent)
        {
            Uri uri = new Uri(url);
            HttpClientHandler handler = new HttpClientHandler();
            handler.CookieContainer = new CookieContainer();
            foreach (var cookie in cookieContent)
            {
                handler.CookieContainer.Add(uri, new Cookie(cookie.Key, cookie.Value));
            }
            HttpClient client = new HttpClient(handler);
            Console.Write("远程HttpGet调用：URL：" + url + ",Cookie:" + JsonExtensions.ToJson(cookieContent));
            HttpResponseMessage responseMsg = client.GetAsync(url).Result;
            var responseContent = responseMsg.Content.ReadAsStringAsync().Result;
            if (responseMsg.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new HttpRequestException(string.Format("调用{0}接口出错！StatusCode：{1}，Msg：{2}",
                url, responseMsg.StatusCode, responseContent));
            }
            Console.Write("远程HttpGet调用结果：URL：" + url + "，结果:" + responseContent);
            return responseContent;
        }
        public static string HttpPostWithCookieV2(string url, object data, KeyValuePair<string, string> cookies)
        {
            //设置cookie
            HttpClientHandler handler = new HttpClientHandler
            {
                UseCookies = false
            };
            var client = new HttpClient(handler);
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Cookie", string.Format("{0}={1}", cookies.Key, cookies.Value));
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"); // 设置请求头消息User-Agent
                                                                                                                                             //specify to use TLS 1.2 as default connection
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            var result = client.PostAsync(url, new StringContent(JsonExtensions.ToJson(data), Encoding.UTF8, "application/json")).Result;
            var responseContent = result.Content.ReadAsStringAsync().Result;
            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new HttpRequestException(string.Format("调用{0}接口出错！StatusCode：{1}，Msg：{2}",
                url, result.StatusCode, responseContent));
            }
            Console.Write("远程带Cookie-Post调用结果：URL：" + url + "，结果:" + responseContent);
            return responseContent;

        }
        public static string HttpPostWithCookie(string url, object data, KeyValuePair<string, string> cookies)
        {
            //设置cookie
            HttpClientHandler handler = new HttpClientHandler
            {
                UseCookies = false
            };
            var client = new HttpClient(handler);
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url))
            {
                request.Headers.Add("Cookie", string.Format("{0}={1}", cookies.Key, cookies.Value));
                request.Content = new StringContent(JsonExtensions.ToJson(data), Encoding.UTF8, "application/json");
                //specify to use TLS 1.2 as default connection
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                var result = client.SendAsync(request).Result;
                var responseContent = result.Content.ReadAsStringAsync().Result;
                if (result.StatusCode != HttpStatusCode.OK)
                {
                    throw new HttpRequestException(string.Format("调用{0}接口出错！StatusCode：{1}，Msg：{2}",
                    url, result.StatusCode, responseContent));
                }
                Console.Write("远程带Cookie-Post调用结果：URL：" + url + "，结果:" + responseContent);
                return responseContent;
            }
        }
        public static async Task<string> HttpPostAsync(IHttpClientFactory httpClientFactory, string url, string data)
        {
            var request = new StringContent(data);
            request.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var responseMsg = await httpClientFactory.CreateClient().PostAsync(url, request);
            var responseContent = await responseMsg.Content.ReadAsStringAsync();
            if (responseMsg.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new HttpRequestException($"调用{url}接口出错！StatusCode：{responseMsg.StatusCode}，Request：{request}");
            }
            return responseContent;
        }

    }
}
